#include "MList.h"
/*
MList * createMList(ListType lType)
{
	MList *ml= (MList*) malloc(sizeof(MList));
	ml->head=0;
	ml->tail=0;
	ml->lType=lType;
	ml->count=0;
	ml->name="No Name";
	InitializeCriticalSection(&(ml->cs));
	return ml;
}
*/
MList * createMList(ListType lType,char * name)
{
	MList *ml= (MList*) malloc(sizeof(MList));
	ml->head=0;
	ml->tail=0;
	ml->lType=lType;
	ml->count=0;
	ml->name=name;
	InitializeCriticalSection(&(ml->cs));
	return ml;
}

void M_insert(int value, MList *list)
{
	EnterCriticalSection(&(list->cs));
	if(list->head==0)
	{
		Node *node=(Node*)malloc(sizeof(Node));
		node->value=value;
		node->next=0;
		list->head=node;
		list->tail=node;
		list->count++;
	}
	else{
		Node *p,*q;
		p=list->head;
		q=p;
		while(p!=0)
		{
			if((list->lType==LargeHead&&p->value<value)||(list->lType==LargeTail&&p->value>value))
			{
				Node *node=(Node*)malloc(sizeof(Node));
				node->value=value;
				node->next=p;
				if(q==p)list->head=node;
				else q->next=node;
				list->count++;
				break;
			}else 
				if(p->value==value)
				{
					break;
				}
				else
				{
					q=p;
					p=q->next;
				}
		}
		if(p==0){
			Node *node=(Node*)malloc(sizeof(Node));
			node->value=value;
			node->next=0;
			q->next=node;
			list->tail=node;
			list->count++;
		}
	}
	//printMList(list);
	LeaveCriticalSection(&(list->cs));
}

int M_pop(MList *list)
{
	Node *p;
	int r;
	EnterCriticalSection(&list->cs);
	p=list->head;

	if(p!=0)
	{
		r=p->value;
		list->head=p->next;
		free(p);
		list->count--;
	}
	//printMList(list);
	LeaveCriticalSection(&list->cs);
	return r;
}

int M_first(MList *list){
	Node *p;	
	int r=-9999;
	EnterCriticalSection(&list->cs);
	p=list->head;
	if(p!=0)r=p->value;
	LeaveCriticalSection(&list->cs);
	return r;
}
int M_count(MList *list)
{
	return list->count;
}

int M_hasElements(MList *list)
{
	return (list->count>0)?1:0;
}

void printMList(MList *list)
{
	//EnterCriticalSection(&list->cs);
	Node *p;
	p=list->head;
	printf("%s:",list->name);
	while(p!=0)
	{
		printf("%d,",p->value);
		p=p->next;
	}
	printf("\n");
	//LeaveCriticalSection(&list->cs);
}
